#ifndef __DSTH_CHANNEL_BUFFER_H__
#define __DSTH_CHANNEL_BUFFER_H__

#include <string>
#include "DSTHType.h"

namespace dsth {

class ChannelBuffer {
public:
    ChannelBuffer();
    explicit ChannelBuffer(size_t initSize);
    ~ChannelBuffer();
    char* GetWriter() { return writer_; }
    void Retrieve(size_t n) { reader_ += n; }
    void RetrieveAll() { writer_ = reader_ = begin_ + kPrependSize; }
    int ReadFd(int fd, int* err);
    int WriteFd(int fd);
    std::string FetchAsString();
    int32_t FetchAsInt32();

    int32_t PeekInt32();
    void Perpend(const void* data, size_t len);
    void Append(const char* data, size_t len);
    void Append(const void* data, size_t len);
    void AppendInt32(int32_t x);
    void AppendInt16(int16_t x);
    size_t ReadableBytes() const { return writer_ - reader_; }
    size_t WritableBytes() const { return end_ - writer_;    }
    size_t PrependableBytes() const { return begin_ - reader_; }
    const char* Peek() const { return reader_; }
    void EnsureCapacity(size_t len);
    void HasWritten(size_t len);
private:
    static const int kPrependSize;
    static const int kInitSize;

    void IncreaseCapacity(size_t len);
    char* begin_;
    char* end_;
    char* writer_;
    char* reader_;
};

} // namespace
#endif // __DSTH_CHANNEL_BUFFER_H__

